﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class PoolManage: MonoBehaviour
{
    public GameObject _poolObjPrefab;

    public LinkedList<GameObject> _poolObjs;
    public LinkedList<GameObject> _usedObjs;
    public int _poolLength { get; private set; }//设置对象数量
    void Start()
    {
        //Init();
    }

    private void Update()
    {
        //Debug.Log(_poolObjs == null);
    }
    public static PoolManage CreatePool(string name)
    {
        PoolManage pm = new GameObject(name,typeof(PoolManage)).GetComponent<PoolManage>();
        return pm;
    }

    public void Init(int size,GameObject poolObj)
    {
        _poolObjs = new LinkedList<GameObject>();
        _usedObjs = new LinkedList<GameObject>();
        Debug.Log(_poolObjs == null);
        _poolObjPrefab = poolObj;
        InitPoolObjs(size);
    }

    protected void InitPoolObjs(int poolSize)//实例化空对象载体，填满池子
    {
        _poolLength = poolSize;

        for (int i=0; i< _poolLength; ++i)
        {
            _poolObjs.AddLast(CreatePoolObj());
            _poolObjs.Last.Value.SetActive(false);
        }
    }

    protected virtual GameObject CreatePoolObj()//创建对象池物体
    {
        GameObject o=Instantiate(_poolObjPrefab, this.transform);
        PoolObj po= o.AddComponent<PoolObj>();
        po.SetPoolObj(this);
        return o;
    }

    /// <summary>
    /// 从池子取出 预制体使用
    /// </summary>
    /// <returns></returns>
    public GameObject InsPoolObj()
    {
        GameObject obj;

        //Debug.Log(_poolObjs == null);
        if (_poolObjs.Count > 0)
        {
            obj = _poolObjs.Last.Value;
            _poolObjs.RemoveLast();
            _usedObjs.AddLast(obj);
            obj.SetActive(true);
            return obj;
        }
        else
            Debug.LogWarning("pool obj is null");
            return null;
    }

    public virtual void RecyclePoolObj(GameObject obj)//回收实例载体
    {
        PoolObj po = obj.GetComponent<PoolObj>();
        if (po!=null&&po._poolParent==this)
        {
            _usedObjs.Remove(obj);
            _poolObjs.AddLast(obj);
            obj.transform.SetParent(this.transform);
            obj.SetActive(false);
        }
    }

    public void RecycleAllPoolObj()
    {
        while (true)
        {
            if (_usedObjs.Count > 0)
            {
                RecyclePoolObj(_usedObjs.Last.Value);
            }
            else break;
        }
    }
}
